package org.mobiletrain.www.secondproject2;

import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

import Utils.ImageUtils;
import Utils.JsonUtil;
import adapter.TopPagerAdapter;
import adapter.TuiJianAdapter;
import bean.TopPagerData;
import bean.TuiJian;


public class ShouYeFragment extends Fragment {

    private static final String TAG ="ShouYeFragment" ;
    private ArrayList<TuiJian> tuiJians;
    private TuiJianAdapter adapter;
    private String cityCode;
    private String cityName;
    private String cityId;
    private ArrayList<TopPagerData> topPagerDatas;
    private TopPagerAdapter topPagerAdapter;
    private RadioGroup radioGroupPager;
    private ArrayList<TopPagerData> topButtonDatas;
    private String titleAlias;
    private String app_picpath;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_shou_ye, container, false);

        Bundle bundle = getArguments();
        cityCode = bundle.getString("cityCode");
        cityId = bundle.getString("cityId");
        cityName = bundle.getString("cityName");

       Log.i(TAG, "==============" + cityCode);
       Log.i(TAG,"=============="+cityName);
       Log.i(TAG,"=============="+cityId);

        PullToRefreshListView refreshListView =
                (PullToRefreshListView) view.findViewById(R.id.shouye_list);
        ListView shouyeList = refreshListView.getRefreshableView();
        ProgressBar bar = (ProgressBar) view.findViewById(R.id.shouye_bar);
        shouyeList.setEmptyView(bar);
        View topView = inflater.inflate(R.layout.topfragment_layout,null);
        ViewPager topPager = (ViewPager) topView.findViewById(R.id.top_pager);

        radioGroupPager = (RadioGroup) topView.findViewById(R.id.radio_group_pager);

        topButtonDatas = new ArrayList<TopPagerData>();
        getTopPagerData(cityCode);




        //ViewPager的五个RadioButton
        RadioButton rbPager=(RadioButton)radioGroupPager.getChildAt(0);
        rbPager.setChecked(true);
        rbPager.setBackgroundColor(Color.BLUE);


        //五个选项按钮的RarioButton
        topButtonDatas = new ArrayList<TopPagerData>();
        getTopPagerData(cityCode);
        RadioGroup radioGroup = (RadioGroup) topView.findViewById(R.id.radio_group_button);


        for (int i = 0; i <topButtonDatas.size() ; i++) {

            RadioButton rbtns = (RadioButton) radioGroup.getChildAt(i);
            ImageUtils.getBitmapUtils(getActivity()).display(rbtns,topButtonDatas.get(i).getApp_picpath());
            rbtns.setText(topButtonDatas.get(i).getTitle());
        }




        topPagerDatas = new ArrayList<TopPagerData>();

        topPagerAdapter = new TopPagerAdapter(topPagerDatas, getActivity());
        topPager.setAdapter(topPagerAdapter);

        getTopPagerData(cityCode);




        topPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                RadioButton rbtn = (RadioButton) radioGroupPager.getChildAt(position);
                rbtn.setChecked(true);
                rbtn.setBackgroundColor(Color.BLUE);

            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

        shouyeList.addHeaderView(topView);

        view.findViewById(R.id.wenquan).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                
            }
        });


        //给ListView设置到界面上显示
        tuiJians = new ArrayList<TuiJian>();
        adapter = new TuiJianAdapter(tuiJians, getActivity());
        shouyeList.setAdapter(adapter);
        getListData(cityCode);

        return view;
    }


    public void getTopPagerData(String cityCode){
        String path="http://apiphp.yaochufa.com/you/advertiselist/AdList?column=bannerRound%2CbannerScroll%2CbannerSquare%2CappBannerPop&area_code="+cityCode+"&version=4.2.2&imei=865026028677325&system=android&deviceToken=865026028677325&regId=d%2F%2FigwEhgBGCI2TG6lWqlMRlRShextvVmBSWhZd6jbxzxaP83EveyU%2B4i9O7wvq0OfWexSmIGrjonpYK4Vo%2FrEiWAneGT%2F6VaPEQ7lMK8WE%3D&channel=yaochufa";
        JsonUtil.loadJson(getActivity(),path,new JsonUtil.OnJsonDown() {
            @Override
            public void ok(String json) {
                Log.i(TAG,"=========="+json);
                try {
                    JSONObject jsonObject = new JSONObject(json);
                    JSONArray content = jsonObject.getJSONArray("content");
                    for (int i = 0; i <content.length() ; i++) {
                        JSONObject object = content.getJSONObject(i);
                        titleAlias = object.getString("titleAlias");

                        if (titleAlias.equals("bannerScroll")){
                            JSONArray sad = object.getJSONArray("ad");
                            for (int j = 0; j <sad.length() ; j++) {
                                JSONObject obj = sad.getJSONObject(j);
                                String adKey = obj.getString("adKey");
                                JSONObject ct = obj.getJSONObject("ct");
                                String app_picpath = ct.getString("app_picpath");
                                String app_url_site = ct.getString("app_url_site");
                                String app_url = ct.getString("app_url");
                                String adId = ct.getString("adId");
                                String title = ct.getString("title");
                                String appToUrl = ct.getString("appToUrl");


                                TopPagerData topPagerData =
                                        new TopPagerData(titleAlias,adKey,app_picpath,app_url_site,app_url,adId,appToUrl,title);
                                topPagerDatas.add(topPagerData);

                            }
                        }
                        if (titleAlias.equals("bannerRound")) {
                            JSONArray sad = object.getJSONArray("ad");
                            for (int j = 0; j < sad.length(); j++) {
                                JSONObject obj = sad.getJSONObject(j);
                                String adKey = obj.getString("adKey");
                                JSONObject ct = obj.getJSONObject("ct");
                                app_picpath = ct.getString("app_picpath");
                                String app_url_site = ct.getString("app_url_site");
                                String app_url = ct.getString("app_url");
                                String adId = ct.getString("adId");
                                String title = ct.getString("title");
                                String appToUrl = ct.getString("appToUrl");


                                TopPagerData topButtonData =
                                        new TopPagerData(titleAlias, adKey, app_picpath, app_url_site, app_url, adId, appToUrl, title);
                                topButtonDatas.add(topButtonData);


                            }
                        }
                        /* JSONArray sad = object.getJSONArray("ad");
                            for (int j = 0; j <sad.length() ; j++) {
                            JSONObject obj = sad.getJSONObject(j);
                            String adKey = obj.getString("adKey");
                            JSONObject ct = obj.getJSONObject("ct");
                            String app_picpath = ct.getString("app_picpath");
                            String app_url_site = ct.getString("app_url_site");
                            String app_url = ct.getString("app_url");
                            String adId = ct.getString("adId");
                            String title = ct.getString("title");
                            String appToUrl = ct.getString("appToUrl");


                            TopPagerData topPagerData =
                                    new TopPagerData(titleAlias,adKey,app_picpath,app_url_site,app_url,adId,appToUrl,title);
                            topPagerDatas.add(topPagerData);

                        }*/


                    }
                   topPagerAdapter.notifyDataSetChanged();
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void error(String error) {

            }
        });



    }


    public void getListData(String cityCode){
        HttpUtils utils = new HttpUtils();
        String listPath="http://apiphp.yaochufa.com/playpoint/recommend?userId=&longitude=0.0&latitude=0.0&version=4.2.2&imei=865026028677325&system=android&deviceToken=865026028677325&regId=d%2F%2FigwEhgBGCI2TG6lWqlMRlRShextvVmBSWhZd6jbxzxaP83EveyU%2B4i9O7wvq0OfWexSmIGrjonpYK4Vo%2FrEiWAneGT%2F6VaPEQ7lMK8WE%3D&channel=yaochufa&city="+cityCode;
        utils.send(HttpRequest.HttpMethod.GET,listPath,new RequestCallBack<Object>() {
            @Override
            public void onSuccess(ResponseInfo<Object> objectResponseInfo) {
                String json = objectResponseInfo.result.toString();

                try {
                    JSONObject jsonObject = new JSONObject(json);
                    JSONArray content = jsonObject.getJSONArray("content");
                    for (int i = 0; i <content.length() ; i++) {
                        JSONObject object = content.getJSONObject(i);
                        String productId = object.getString("productId");
                        String productName = object.getString("productName");
                        String productDescription = object.getString("productDescription");
                        String productTitle = object.getString("productTitle");
                        String productTitleContent = object.getString("productTitleContent");
                        String mImageUrl = object.getString("mImageUrl");
                        String url = object.getString("url");
                        String retailPrice = object.getString("retailPrice");
                        String price = object.getString("price");
                        String originalPrice = object.getString("originalPrice");
                        String saledCount = object.getString("saledCount");
                        String provinceName = object.getString("provinceName");
                        String cityName1 = object.getString("cityName");
                        String adress1 = object.getString("adress");
                        if (object.has("tags")){
                            JSONArray tags = object.getJSONArray("tags");


                        }

                        TuiJian tuiJian = new TuiJian(productId, productName, productDescription, productTitle, productTitleContent, mImageUrl, url, retailPrice, price, originalPrice, saledCount, provinceName, cityName1, adress1);
                        tuiJians.add(tuiJian);


                    }
                    adapter.notifyDataSetChanged();

                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onFailure(HttpException e, String s) {
                Toast.makeText(getActivity(),"下载失败",Toast.LENGTH_SHORT).show();
            }
        });
    }



}
